<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of reportes
 *
 * @author migueln
 */
include "util.php";

class reportes {

    public static $datat = array();
    public static $datarep = array();

    public function generateReporteIncidenciasSubmotivo($fecha_inicio, $fecha_fin, $motivo_id = null, $submotivo_id = null, $categoria_id = null, $zona_id = null) {

        $report = array();
        self::$datarep = array();
        $fechaInicio = new DateTime($fecha_inicio);
        $fechaFin = new DateTime($fecha_fin);
        $fechaFin->modify('+1 day');
        $datareporteortes = static:: dataReporteIncPieSubmo($fechaInicio->format('Y-m-d 00:00:00'), $fechaFin->format('Y-m-d 23:59:59'), $motivo_id, $submotivo_id, $categoria_id, $zona_id);
        $data_names = Util::array_column($datareporteortes, "name");
        $data_names = array_unique($data_names);
        $dataEtapas = array();
        foreach ($data_names as $key) {
            array_push($dataEtapas, array('name' => $key));
        }
        self::$datarep = $dataEtapas;
        foreach (self::$datarep as $key => $value) {
            self::$datarep[$key]["data"] = array();
        }
        foreach (Util::array_column($dataEtapas, 'name') as $key => $value) {
            self::$datat = array();
            $date = $value;
            $this->recursive_array_search($date, $datareporteortes);
            $dataEsatdosReporte = util::array_column(self::$datat, "name");
            $estadosFalta = array_diff(util::array_column($dataEtapas, 'name'), $dataEsatdosReporte);
            if ($estadosFalta) {
                foreach ($estadosFalta as $value) {
                    self::$datat[] = array("name" => $value, 'data' => 0);
                }
            }
            foreach (self::$datarep as $key => $value) {
                foreach (self::$datat as $valuet) {
                    if ($value["name"] == $valuet["name"]) {
                        self::$datarep[$key]['data'][] = $valuet["data"];
                    }
                }
            }
        }
        $dataserie = array("type" => "pie", "name" => "Incidencia Producto", "data" => array());
        array_walk(self::$datarep, function ($value, $key) {
            self::$datarep[$key]['data'] = array_sum($value['data']);
        });
        foreach (self::$datarep as $rep) {
            $dataserie["data"][] = array($rep['name'], $rep['data']);
        }
        $report['title']['text'] = 'Incidencias';
        $report['credits']['enabled'] = false;
        $report['chart']['height'] = '400';
        $report['plotOptions'] = array(
            'pie' => array(
                'allowPointSelect' => true,
                'cursor' => 'pointer',
                'dataLabels' => array(
                    'enabled' => false,
                    'format' => '<b>{point.name}</b>: {point.percentage:.1f} %'
                ),
                'showInLegend' => true,
                'tooltip' => array(
                    'pointFormat' => 'Porcentaje: <b>{point.percentage:.1f}%</b><br>{series.name}: <b>{point.y}</b>'
                ),
            )
        );
        $report["series"][] = $dataserie;
        $report['mostrar'] = Producto::model()->mostrarInformacion($report['series']);
        return $report;
    }

    private function dataReporteIncPieSubmo($fecha_incio, $fecha_fin, $motivo_id = null, $submotivo_id = null, $categoria_id = null, $zona_id = null) {

//        SELECT
//        t.producto_id,
//        sum(t.cantidad) AS total,
//        isu.nombre,
//        isu.id
//        FROM incidencia_producto t
//        INNER JOIN incidencia i ON i.id = t.incidencia_id
//        INNER JOIN incidencia_submotivo isu ON isu.id = i.incidencia_submotivo_id
//        GROUP BY isu.id
//        ORDER BY total DESC
//        LIMIT 5;
        $command = Yii::app()->db->createCommand();
        $command->select("t.producto_id ,sum(t.cantidad) AS total, isu.nombre as name,isu.id as submotivo_id")
                ->from($this->tableName() . " as t")
                ->join("incidencia i", "i.id = t.incidencia_id")
                ->join("cuenta cu", "i.cuenta_id = cu.id")
                ->join('zona zo', 'cu.zona_id=zo.id')
                ->join("incidencia_submotivo isu", "isu.id = i.incidencia_submotivo_id")
                ->join("producto pr", "t.producto_id = pr.id")
        ;
//        var_dump($submotivo_id);
        if ($submotivo_id) {
            $command->andWhere(array('in', 'i.incidencia_submotivo_id', Util::arrayParseInt(explode(',', $submotivo_id))));
        }
        if ($motivo_id) {
            $command->andWhere(array('in', 'isu.incidencia_motivo_id', Util::arrayParseInt(explode(',', $motivo_id))));
        }
        if ($categoria_id) {
            $command->andWhere("pr.categoria_id=:categoria_id", array(':categoria_id' => $categoria_id));
        }
        if ($zona_id) {
            $command->andWhere(array('in', 'zo.id', Util::arrayParseInt(explode(',', $zona_id))));
        }
        $command->andWhere("i.estado=:estado AND i.fecha_creacion BETWEEN :fecha_inicio AND :fecha_fin", array(
            ":estado" => self::ESTADO_ACTIVO,
            ":fecha_inicio" => $fecha_incio,
            ":fecha_fin" => $fecha_fin
        ));
        $command->group("isu.id");
        $command->order("total desc");
        $command->limit(10);
        $result = $command->queryAll();
//        var_dump($result) ;
        return $result;
    }

    //put your code here
    private static function recursive_array_search($needle, $haystack) {
        foreach ($haystack as $value) {
            if ($needle === $value OR ( is_array($value) && static::recursive_array_search($needle, $value))) {
                self::$datat[] = array("name" => $haystack["name"], "data" => (int) $haystack["total"]);
            }
        }
    }

}
